package com.software.human.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.software.human.R;
import com.software.human.adapters.UserInfoAdapter;
import com.software.human.entity.UserInfo;
import com.software.human.util.OkHttpUtil;
import com.software.human.util.PageResult;
import com.software.human.util.Result;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class UserInfoListActivity extends AppCompatActivity {

    private Button btn_user_add;
    private ListView lv_user;
    private UserInfoAdapter adapter;
    private Button btn_search;
    private EditText edt_user_name_search;
    private SmartRefreshLayout srl_user;

    private int pageNum = 1;
    private int pageSize = 3;
    private boolean isRefresh = true;
    private int totalPage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info_list);
        initViews();
        initEvents();
        initAdapter();
    }

    private void initAdapter() {
        adapter = new UserInfoAdapter(this, R.layout.user_item, new ArrayList<>());
        lv_user.setAdapter(adapter);
    }

    private void initEvents() {
        btn_user_add.setOnClickListener(v -> {
            Intent intent = new Intent(this, UserInfoAddActivity.class);
            startActivity(intent);
        });

        btn_search.setOnClickListener(v -> {
            String searchName = edt_user_name_search.getText().toString();
            if (searchName.isEmpty()) {
                Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();
                return;
            }
            queryUserInfo(searchName);
            // 获取网络连接
            // 访问后台的数据接口
            OkHttpClient okHttp = OkHttpUtil.getInstance("");
            String url = getString(R.string.system_url);
        });

        lv_user.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                UserInfo userInfo = (UserInfo) adapter.getItem(position);
                AlertDialog.Builder builder = new AlertDialog.Builder(UserInfoListActivity.this);
                builder.setTitle("确定");
                builder.setMessage("您确定要删除此条数据吗");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        deleteUserInfo(userInfo.getUserId());
                        
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        
                    }
                });
                builder.create().show();
                // true为事件拦截，长按事件后面是点击事件，如果不拦截，会触发两次事件
                return true;
            }
        });

        // 下拉刷新接口
        srl_user.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                isRefresh = true;
                pageNum = 1;
                String searchName = edt_user_name_search.getText().toString();
                queryUserInfo(searchName);

            }
        });
        // 上拉加载更多接口
        srl_user.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isRefresh = false;
                pageNum ++;
                // pageNum++后的值不能大于总页数
                if (pageNum == totalPage) {

                    Toast.makeText(UserInfoListActivity.this, "已经到底了", Toast.LENGTH_SHORT).show();
                    srl_user.finishLoadMore();
                    return;
                }
                String searchName = edt_user_name_search.getText().toString();
                queryUserInfo(searchName);

            }
        });
    }

    private void deleteUserInfo(String userId) {
        String utl = getString(R.string.system_url);
        OkHttpClient okHttp = OkHttpUtil.getInstance("");
        Request request = new Request.Builder()
                .get()
                .url(utl + "/userInfo/delete?userId=" + userId)
                .build();
        Call call = okHttp.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {

            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    String body = response.body().string();
                    Gson gson = new Gson();
                    Result<UserInfo> result = gson.fromJson(body, new TypeToken<Result<UserInfo>>() {
                    }.getType());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (result.getCode() != 200) {
                                Toast.makeText(UserInfoListActivity.this, result.getMsg(), Toast.LENGTH_SHORT).show();
                            } else {
                                String searchName = edt_user_name_search.getText().toString();
                                queryUserInfo(searchName);
                                Toast.makeText(UserInfoListActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }

            }
        });

        lv_user.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(
                        UserInfoListActivity.this,
                        UserInfoViewActivity.class
                );
                // 在跳转的时候，将数据传递过去
                // 1、传递userId，跳转后调用后台接口获取数据

                // 2、传递整个对象
                UserInfo userInfo = (UserInfo) adapter.getItem(position);
                intent.putExtra("userInfo", userInfo);
                startActivity(intent);

            }
        });
    }

    private void initViews() {
        btn_user_add = findViewById(R.id.btn_user_add);
        lv_user = findViewById(R.id.lv_user);
        edt_user_name_search = findViewById(R.id.edt_user_name_search);
        btn_search = findViewById(R.id.btn_search);

        srl_user = findViewById(R.id.srl_user);
    }

    @Override
    protected void onStart() {
        super.onStart();
        queryUserInfo("");
    }

    private void queryUserInfo(String searchName) {
        // 获取网络连接
        // 访问后台的数据接口
        OkHttpClient okHttp = OkHttpUtil.getInstance("");
        String url = getString(R.string.system_url);

        Request request = new Request.Builder()
                .get() // 这是默认请求
                .url(url + "/userInfo/query?pageNum=" + pageNum + "&pageSize="+ pageSize +"&userName=" + searchName)
                .build();

        Call call = okHttp.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {

            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    String body = response.body().string();
                    Gson gson = new Gson();
                    Result<PageResult<List<UserInfo>>> result = gson.fromJson(
                            body,
                            new TypeToken<Result<PageResult<List<UserInfo>>>>(){}.getType()
                    );

                    // 更新UI
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (result .getCode() != 200) {
                                Toast.makeText(UserInfoListActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
                            } else {
                                // 更新adapter的数据源
                                totalPage = result.getData().getTotalPage();

                                if (isRefresh) {
                                    srl_user.finishRefresh();
                                    adapter.updateData(result.getData().getData());
                                } else {
                                    adapter.loadMore(result.getData().getData());
                                    srl_user.finishLoadMore();
                                }

                            }
                        }
                    });
                }



            }
        });

    }
}